package comgutianyu.qihangjiaoyu.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import comgutianyu.qihangjiaoyu.R;
import comgutianyu.qihangjiaoyu.model.LessonItem;
import java.util.List;

public class LessonListAdapter extends RecyclerView.Adapter<LessonListAdapter.ViewHolder> {
    private List<LessonItem> lessonItems;
    private OnItemClickListener listener;
    private int currentPlayingPosition = -1;

    public interface OnItemClickListener {
        void onItemClick(LessonItem item, int position);
    }

    public LessonListAdapter(List<LessonItem> lessonItems) {
        this.lessonItems = lessonItems;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_lesson, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        LessonItem item = lessonItems.get(position);
        holder.titleText.setText(item.getTitle());
        holder.durationText.setText(item.getDuration());
        
        // 设置播放状态图标
        holder.playingIcon.setVisibility(position == currentPlayingPosition ? View.VISIBLE : View.GONE);
        
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(item, position);
                setPlayingPosition(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return lessonItems.size();
    }

    public void setPlayingPosition(int position) {
        int oldPosition = currentPlayingPosition;
        currentPlayingPosition = position;
        if (oldPosition != -1) {
            notifyItemChanged(oldPosition);
        }
        if (position != -1) {
            notifyItemChanged(position);
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView titleText;
        TextView durationText;
        ImageView playingIcon;

        ViewHolder(View view) {
            super(view);
            titleText = view.findViewById(R.id.lessonTitle);
            durationText = view.findViewById(R.id.lessonDuration);
            playingIcon = view.findViewById(R.id.playingIcon);
        }
    }
} 